package com.atguigu.gulimail.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimail.product.service.CategoryBrandRelationService;
import com.atguigu.gulimail.product.vo.CataLog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public PageUtils queryPage (Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree () {
        //查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子结构的树状结构
        //2.1 找出所有的一级分类
        List<CategoryEntity> level1Menus =
                entities.stream().filter(
                        categoryEntity -> categoryEntity.getParentCid() == 0
                ).map((menu) -> {
                            menu.setChildren(getChildrens(menu, entities));
                            return menu;
                        }
                ).sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return level1Menus;
    }

    //自定义的删除菜单的方法
    @Override
    public void removeByMenuIds (List<Long> asList) {
        //TODO  检查当前删除的菜单是否被别的地方引用
        log.info("remove ids ==>, {}", JSONObject.toJSONString(asList));
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] finCatelogPath (Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade (CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }


    //225  25  2
    private List<Long> findParentPath (Long catelogId, List<Long> paths) {
        //1.收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens (CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == root.getCatId();
                }
        ).map(categoryEntity -> {
            //1.找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2.菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    /**
     * 查找所有一级分类信息
     *
     * @return
     */
    @Override
    public List<CategoryEntity> selectCategoryLevl1 () {
        List<CategoryEntity> parent_ids = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", "0"));
        return parent_ids;
    }

    @Override
    public Map<String, List<CataLog2Vo>> getCatalogJson () throws InterruptedException {
        //先从缓存获取数据
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        String catalogs = stringStringValueOperations.get("catalogs");
        //缓存有数据则直接返回缓存数据
        if (StringUtils.isEmpty(catalogs)) {
            log.info("缓存未命中，准备查询DB,线程ID，{}", Thread.currentThread().getId());
            //为空则查数据库
            Map<String, List<CataLog2Vo>> catalogJsonForDB = getCatalogJsonForDBRedissionLock();
            return catalogJsonForDB;
        }
        log.info("缓存命中，直接返回");
        Map<String, List<CataLog2Vo>> stringListMap = JSON.parseObject(catalogs, new TypeReference<Map<String, List<CataLog2Vo>>>() {
        });

        return stringListMap;
    }

    private Map<String, List<CataLog2Vo>> getCatalogJsonForDBRedisLock () throws InterruptedException {
        //使用分布式锁
        String uuid = UUID.randomUUID().toString();
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        Boolean redisLock = stringStringValueOperations.setIfAbsent("redisLock", uuid, 15, TimeUnit.SECONDS);
        if (redisLock) {
            log.info("查询categorys-------获取redis锁");
            Map<String, List<CataLog2Vo>> stringListMap;
            try {
                stringListMap = getStringListMap(stringStringValueOperations);
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("redisLock"), uuid);
            }

            return stringListMap;
        } else {
            //加锁失败 重试
            log.info("查询categorys-------未获取redis锁");
            Thread.sleep(100);
            return getCatalogJsonForDBRedisLock();
        }
    }

    private Map<String, List<CataLog2Vo>> getCatalogJsonForDBRedissionLock () {
        //使用redission
        RLock lock = redissonClient.getLock("product-getCatalogJson");
        lock.lock(10, TimeUnit.SECONDS);
        log.info("查询categorys---->线程:" + Thread.currentThread().getId() + "获取了redission锁");
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        Map<String, List<CataLog2Vo>> stringListMap;
        try {
            stringListMap = getStringListMap(stringStringValueOperations);
        } finally {
            lock.unlock();
        }
        return stringListMap;

    }

    private Map<String, List<CataLog2Vo>> getStringListMap (ValueOperations<String, String> stringStringValueOperations) {
        String catalogs = stringStringValueOperations.get("catalogs");
        if (!StringUtils.isEmpty(catalogs)) {
            log.info("再次查询缓存命中，返回缓存数据");
            return JSON.parseObject(catalogs, new TypeReference<Map<String, List<CataLog2Vo>>>() {});
        }
        log.info("第二次查询缓存未命中，查询DB");
        //将数据库多次查询变为一次
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有一级分类
        List<CategoryEntity> categoryEntityList = getParentCid(selectList, 0L);

        //封装数据
        Map<String, List<CataLog2Vo>> listMap = categoryEntityList.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntityList1 = getParentCid(selectList, v.getCatId());
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CataLog2Vo> cateLog2VoList = null;
            if (categoryEntityList1.size() > 0) {
                cateLog2VoList = categoryEntityList1.stream().map(l2 -> {
                    CataLog2Vo cateLog2Vo = new CataLog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());
                    //找当前二级分类的三级分类
                    List<CategoryEntity> categoryEntityListLevel3 = getParentCid(selectList, l2.getCatId());
                    if (categoryEntityListLevel3.size() > 0) {
                        //封装3级分类为指定格式
                        List<CataLog2Vo.Catalog3Vo> catelog3VoList = categoryEntityListLevel3.stream().map(l3 -> {
                            CataLog2Vo.Catalog3Vo catelog3Vo = new CataLog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        cateLog2Vo.setCatalog3List(catelog3VoList);

                    }

                    return cateLog2Vo;
                }).collect(Collectors.toList());
            }
            return cateLog2VoList;
        }));
        stringStringValueOperations.set("catalogs", JSONObject.toJSONString(listMap), 1, TimeUnit.DAYS);
        return listMap;
    }

    //同步方法查询数据库
    private synchronized Map<String, List<CataLog2Vo>> getCatalogJsonForDB () {

        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        return getStringListMap(stringStringValueOperations);
    }


    private List<CategoryEntity> getParentCid (List<CategoryEntity> categoryEntityList, Long parentCid) {
        return categoryEntityList.stream().filter(item -> Objects.equals(item.getParentCid(), parentCid)).collect(Collectors.toList());
    }
}